package cn.edu.ncu.housinghub.utils.common;

import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.entity.user.Administrator;
import cn.edu.ncu.housinghub.entity.user.User;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Set;
/**
 * @program: housing-hub
 * @description: 获取用户信息工具类
 * @author: suyu
 **/
@Component
public class TokenUtil {
    @Autowired
    private RedisTemplate redisTemplate;
    private static RedisTemplate tokenRedisTemplate;
    @PostConstruct
    private void init(){
        tokenRedisTemplate = redisTemplate;
    }
    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    public static User getUserByToken(String token) {
        try {
            // 检查token是否为空
            if (token == null || token.trim().isEmpty()) {
                return null;
            }

            // 从Redis中获取用户信息
            String keyPattern = SystemConstant.REDIS_TOKEN_PREFIX_USER.getStringValue() + "*:" + token;
            Set<String> keys = tokenRedisTemplate.keys(keyPattern);
            if (keys == null || keys.isEmpty()) {
                return null;
            }

            String redisKey = keys.iterator().next();
            if (redisKey == null) {
                return null;
            }

            Object userObj = tokenRedisTemplate.opsForValue().get(redisKey);
            if (userObj == null) {
                return null;
            }

            return (User) userObj;
        } catch (Exception e) {
            // 记录错误日志但不抛出异常，返回null表示token无效
            System.err.println("TokenUtil.getUserByToken error: " + e.getMessage());
            return null;
        }
    }
    public static Administrator getAdministratorByToken(String token) {
        try {
            // 检查token是否为空
            if (token == null || token.trim().isEmpty()) {
                return null;
            }

            String keyPattern = SystemConstant.REDIS_TOKEN_PREFIX_ADMIN.getStringValue() + "*:" + token;
            Set<String> keys = tokenRedisTemplate.keys(keyPattern);
            if (keys == null || keys.isEmpty()) {
                return null;
            }

            String redisKey = keys.iterator().next();
            if (redisKey == null) {
                return null;
            }

            Object adminObj = tokenRedisTemplate.opsForValue().get(redisKey);
            if (adminObj == null) {
                return null;
            }

            return (Administrator) adminObj;
        } catch (Exception e) {
            // 记录错误日志但不抛出异常，返回null表示token无效
            System.err.println("TokenUtil.getAdministratorByToken error: " + e.getMessage());
            return null;
        }
    }
}
